package com.hluck.lifecycles

import android.content.Context
import android.os.SystemClock
import android.util.AttributeSet
import android.widget.Chronometer
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

class MyChronometer(val con: Context, val attrs: AttributeSet?=null) : Chronometer(con, attrs),
    LifecycleEventObserver {
    private var elapsedTime: Long = 0

    private fun pauseMeter(){
        elapsedTime = SystemClock.elapsedRealtime() - base
        stop()
    }

    private fun resumeMeter(){
        base = SystemClock.elapsedRealtime() - elapsedTime
        start()
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when(event){
            Lifecycle.Event.ON_PAUSE -> pauseMeter()
            Lifecycle.Event.ON_RESUME -> resumeMeter()
            else -> {}
        }
    }
}
